package mxm.amfire;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.soundcloud.android.crop.Crop;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import dmax.dialog.SpotsDialog;
import me.yokeyword.fragmentation.SupportActivity;
import me.yokeyword.fragmentation.SupportFragment;
import okhttp3.Call;

/**
 * Created by zengpeijin on 2017/2/14.
 */

public class ZhiYunActivity extends SupportActivity implements View.OnClickListener {
    private final int REQUEST_CAMERA=3;
    private RecyclerView mRecyclerView;
    private ImageView imageView;
    private Button btn1, btn2, btn3;
    private Integer res[] = {R.drawable.logo_demo1, R.drawable.logo_demo2, R.drawable.logo_demo3};
    private int index;
    private String mFilePath=Environment.getExternalStorageDirectory()+"/cameratemp/temp.jpg";
    private File selectFile;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_zhiyun);
        initView();

    }


    private void initView() {
        btn1 = (Button) findViewById(R.id.button);
        btn2 = (Button) findViewById(R.id.button2);
        btn3 = (Button) findViewById(R.id.button3);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        imageView = (ImageView) findViewById(R.id.imageView);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        mRecyclerView.setAdapter(new RecyclerView.Adapter<MyViewHolder>() {
            @Override
            public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                MyViewHolder myViewHolder = new MyViewHolder(LayoutInflater.from(ZhiYunActivity.this).inflate(R.layout.recycer_item_zhiyun, null, false));
                return myViewHolder;
            }

            @Override
            public void onBindViewHolder(MyViewHolder holder, int position) {
                holder.iv.setImageResource(res[position]);
                holder.itemView.setTag(position);
                holder.itemView.setOnClickListener(ZhiYunActivity.this);
            }

            @Override
            public int getItemCount() {
                return res.length;
            }

        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
            beginCrop(data.getData());
        } else if (requestCode == Crop.REQUEST_CROP&& resultCode == RESULT_OK) {
            Uri uri=Crop.getOutput(data);
            imageView.setImageURI(uri);
            selectFile=new File(uri.toString());
        }else if( resultCode == RESULT_OK&&requestCode==REQUEST_CAMERA){
            FileInputStream fis = null;
            try {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 4; //图片宽高都为原来的二分之一，即图片为原来的四分之一
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                fis = new FileInputStream(mFilePath); // 根据路径获取数据
                selectFile=new File(mFilePath);
                Bitmap bitmap = BitmapFactory.decodeStream(fis,null,options);
                imageView.setImageBitmap(bitmap);// 显示图片
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if(fis!=null)
                    fis.close();// 关闭流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        System.out.println(requestCode+"----------------------------------------------------------------------             "+resultCode);
    }
    private void beginCrop(Uri source) {
        Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
        Crop.of(source, destination).start(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getTag() != null) {
            selectFile=null;
            index=Integer.valueOf(view.getTag().toString());
            imageView.setImageResource(res[index]);
        } else if (view == btn1) {
                get();
        } else if (view == btn2) {
            Crop.pickImage(this);
        } else if (view == btn3) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 启动系统相机
            File f=new File(mFilePath);
            f.getParentFile().mkdirs();
            Uri photoUri = Uri.fromFile(f); // 传递路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);// 更改系统默认存储路径
            startActivityForResult(intent, REQUEST_CAMERA);
        }
    }
    public File saveBitmapFile(Bitmap bitmap){
        File file=new File(getCacheDir(),"temp.jpg");//将要保存图片的路径

        file.getParentFile().mkdirs();
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
    private void get() {
        final SpotsDialog dialog = new SpotsDialog(this, R.style.spot_dialog_loading);
        dialog.show();
        Map<String, String> params = new HashMap<>();
        params.put("api_key", "ffa6c808999c4199964fd223d3fff47e");
        params.put("api_secret", "fbc720c1bafe484faeabf83332c6b29b");
        if (selectFile == null){
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), res[index]);
            selectFile = saveBitmapFile(bmp);
            bmp.recycle();
            bmp=null;
        }
        if(selectFile.length()>3000000){
            return;
        }
        OkHttpUtils.post().addFile("img","01.jpg",selectFile).params(params).url("https://www.intelvision.cn/api/plate/detection/detect").build().connTimeOut(20000).writeTimeOut(20000).readTimeOut(20000).execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                e.printStackTrace();
                System.out.println("错误");
                dialog.dismiss();
            }

            @Override
            public void onResponse(String response, int id) {
                dialog.dismiss();
                System.out.println(response);
                if (TextUtils.isEmpty(response)) {
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String color = jsonObject.optString("color", "无法识别颜色");
                    String logo = jsonObject.optString("logo", "无法识别车标");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    class MyViewHolder extends RecyclerView.ViewHolder {
        ImageView iv;

        public MyViewHolder(View view) {
            super(view);
            iv = (ImageView) view.findViewById(R.id.imageView);
        }
    }
}
